package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：lintao
 * @date ：Created in 2020/12/4
 * @description ：用户服务接口实现类
 * @version: 1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public User findByUsername(String username) {
        User user  = userDao.findByUsername(username);

        // 判断用户是否禁用
        String station = user.getStation();
        if (!"1".equals(station)){
            return null;
        }

        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles!=null && roles.size() >0){
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions!=null&&permissions.size()>0){
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        // 添加之前先查看该用户名是否已经存在
        User user1 = userDao.findByUsername(user.getUsername());
        if (user1 != null){
            // 该用户名已存在，添加失败
            throw new RuntimeException("该用户名已经存在，请更换用户名");
        }
        // 添加成功
        userDao.add(user);
        // 设置用户与角色的关联关系
        setUserAndRole(user.getId(),roleIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<User> page = userDao.selectCondtion(queryPageBean.getQueryString());
//        for (User user : page) {
//            if (user.getBirthday() == null){
//                continue;
//            }
//            //user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday());
//        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.deleteUserAndRole(user.getId());
        setUserAndRole(user.getId(),roleIds);
        userDao.updateById(user);
    }

    @Override
    public void deleteById(Integer id) {
        userDao.deleteUserAndRole(id);
        userDao.deleteById(id);
    }

    @Override
    public Result findListByUsername(String username) {
        // 根据用户名查找到用户id
        User user = userDao.findByUsername(username);
        Integer userId = user.getId();
        // 根据用户id查询所拥有的角色id
        Integer[] roleIds = userDao.findUserAndRole(userId);
        // 根据角色id查询所能看到的菜单id
        Set<Integer> menuIdSet = new HashSet<Integer>();
        if (roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                List<Integer> menuIds = roleDao.findRoleAndMenu(roleId);
                if (menuIds!=null && menuIds.size()>0){
                    for (Integer menuId : menuIds) {
                        menuIdSet.add(menuId);
                    }
                }
            }
        }

        List<Menu> menuList = new ArrayList<Menu>();

        // 根据菜单id查询其菜单信息
        if (menuIdSet!=null&& menuIdSet.size()>0){
            for (Integer menuid : menuIdSet) {
                Menu menu = menuDao.findOneById(menuid);  // 查询是否是一级菜单
                if(menu == null){ // 不是一级菜单
                    continue;
                }
                // 是一级菜单，继续查询是否有能看到的二级菜单
                List<Menu> ms = new ArrayList<>();
                for (Integer menuid1: menuIdSet){
                    Menu m = menuDao.findTwoByIdAndParentId(menuid1,menu.getId());
                    if(m == null){
                        continue;
                    }
                    // 是其能看到的二级菜单
                    ms.add(m);
                }
                menu.setChildren(ms);
                if (menu.getChildren() == null || menu.getChildren().size() == 0){
                    continue;
                }
                menuList.add(menu);
            }
        }

        return new Result(true,"",menuList);
    }

    @Override
    public Integer[] findUserAndRole(Integer userId) {
        return userDao.findUserAndRole(userId);
    }

    // 设置用户与角色的关联关系
    private void setUserAndRole(Integer userId,Integer[] roleIds){
        if (roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

}
